package com.canaan.business.service.quality.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.canaan.business.common.enums.basic.WhetherEnum;
import com.canaan.business.common.enums.basic.YNEnum;
import com.canaan.business.common.enums.inOutStock.InOrderStatusEnum;
import com.canaan.business.common.enums.inOutStock.InStockOrderTypeEnum;
import com.canaan.business.common.enums.inOutStock.OutOrderStatusEnum;
import com.canaan.business.common.enums.inOutStock.OutStockOrderTypeEnum;
import com.canaan.business.common.enums.invoice.PurchaseReturnBillReturnTypeEnum;
import com.canaan.business.common.enums.quality.QualityProcessModeEnum;
import com.canaan.business.common.enums.quality.QualityResultEnum;
import com.canaan.business.common.enums.quality.QualityTaskStatusEnum;
import com.canaan.business.common.enums.quality.QualityTypeEnum;
import com.canaan.business.common.enums.storehouse.StockQualityStatusEnum;
import com.canaan.business.common.enums.storehouse.StoreHouseTypeEnum;
import com.canaan.business.common.enums.storehouse.StorehouseStockCheckStatusEnum;
import com.canaan.business.common.enums.storehouse.StorehouseStockStatusEnum;
import com.canaan.business.domain.basic.WmsProduct;
import com.canaan.business.domain.basic.WmsStorehouse;
import com.canaan.business.domain.bill.PurchaseReturnBill;
import com.canaan.business.domain.bill.PurchaseReturnBillDetail;
import com.canaan.business.domain.bill.ReceiveProductBill;
import com.canaan.business.domain.inOutStock.*;
import com.canaan.business.domain.quality.ProductQualityItem;
import com.canaan.business.domain.quality.ProductQualityMainTask;
import com.canaan.business.domain.storehouse.WmsStorehouseStock;
import com.canaan.business.mapper.quality.ProductQualityMainTaskMapper;
import com.canaan.business.service.basic.IWmsProductService;
import com.canaan.business.service.basic.IWmsStorehouseService;
import com.canaan.business.service.bill.IPurchaseReturnBillDetailService;
import com.canaan.business.service.bill.IPurchaseReturnBillService;
import com.canaan.business.service.bill.IReceiveProductBillService;
import com.canaan.business.service.inOutStock.*;
import com.canaan.business.service.quality.IProductQualityItemService;
import com.canaan.business.service.quality.IProductQualityMainTaskService;
import com.canaan.business.service.storehouse.IWmsStorehouseStockService;
import com.canaan.common.constant.PrefixConstants;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.DateUtils;
import com.canaan.common.utils.SecurityUtils;
import com.canaan.common.utils.StringUtils;
import com.canaan.common.utils.TableNoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import oshi.driver.mac.net.NetStat;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 物料质检项Service业务层处理
 *
 * @author
 * @date 2023-02-07
 */
@Service
@Slf4j
public class ProductQualityMainTaskServiceImpl implements IProductQualityMainTaskService {
    @Resource
    private ProductQualityMainTaskMapper productQualityMainTaskMapper;
    @Resource
    private IWmsProductService wmsProductService;
    @Resource
    private IProductQualityItemService productQualityItemService;
    @Resource
    private IWmsInStockOrderService inStockOrderService;
    @Resource
    private IWmsInStockDetailOrderService inStockDetailOrderService;
    @Resource
    private IStorehouseStockCheckService storehouseStockCheckService;
    @Resource
    private IReceiveProductBillService receiveProductBillService;
    @Resource
    private IPurchaseReturnBillService returnBillService;
    @Resource
    private IPurchaseReturnBillDetailService returnBillDetailService;
    @Resource
    private IWmsOutStockOrderService wmsOutStockOrderService;
    @Resource
    private IWmsOutStockDetailOrderService wmsOutStockDetailOrderService;
    @Resource
    private IPickerTaskOrderService pickerTaskOrderService;
    @Resource
    private IWmsStockOccupyService wmsStockOccupyService;
    @Resource
    private IWmsStorehouseStockService wmsStorehouseStockService;
    @Resource
    private IWmsStorehouseService storehouseService;
    @Resource
    private IYardageGoodsRecordService yardageGoodsRecordService;


    /**
     * 查询物料质检项
     *
     * @param id 物料质检项主键
     * @return 物料质检项
     */
    @Override
    public ProductQualityMainTask selectProductQualityMainTaskById(Long id) {
        return productQualityMainTaskMapper.selectProductQualityMainTaskById(id);
    }

    /**
     * 查询物料质检项列表
     *
     * @param productQualityMainTask 物料质检项
     * @return 物料质检项
     */
    @Override
    public List<ProductQualityMainTask> selectProductQualityMainTaskList(ProductQualityMainTask productQualityMainTask) {
        return productQualityMainTaskMapper.selectProductQualityMainTaskList(productQualityMainTask);
    }

    /**
     * 新增物料质检项
     *
     * @param productQualityMainTask 物料质检项
     * @return 结果
     */
    @Override
    public int insertProductQualityMainTask(ProductQualityMainTask productQualityMainTask) {
        if(StringUtils.isBlank(productQualityMainTask.getNo())){
            productQualityMainTask.setNo(TableNoUtil.getNo(ProductQualityMainTask.class));
        }
        // 如果是来料检，需要按抽检比例计算抽检数量
        if (QualityTypeEnum.IQC.getCode().equals(productQualityMainTask.getQualityType())||QualityTypeEnum.OQC.getCode().equals(productQualityMainTask.getQualityType())){
            // 查询对应的物料信息
            WmsProduct wmsProduct = wmsProductService.selectWmsProductByProductNo(productQualityMainTask.getProductNo());
            if (wmsProduct.getQualityRatio() != null){
                // 抽检比例存的是百分比制，因此抽检数量结果要除100(总数量*抽检比例/100)
                BigDecimal quantity = productQualityMainTask.getTotalQuantity().multiply(wmsProduct.getQualityRatio()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
                productQualityMainTask.setQuantity(quantity);
            }else {
                productQualityMainTask.setQuantity(productQualityMainTask.getTotalQuantity());
            }
        }
        productQualityMainTask.setCreateBy(SecurityUtils.getUsername());
        productQualityMainTask.setCreateTime(DateUtils.getNowDate());
        return productQualityMainTaskMapper.insertProductQualityMainTask(productQualityMainTask);
    }

    /**
     * 批量新增物料质检项
     *
     * @param productQualityMainTaskList 物料质检项列表
     * @return 结果
     */
    @Override
    public int batchInsertProductQualityMainTask(List<ProductQualityMainTask> productQualityMainTaskList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        // 查询list中的物料
        List<String> productNos = productQualityMainTaskList.stream().map(ProductQualityMainTask::getProductNo).distinct().collect(Collectors.toList());
        List<WmsProduct> productList = this.wmsProductService.selectWmsProductsByProductNos(productNos);
        Map<String,WmsProduct> productMap = productList.stream().collect(Collectors.toMap(WmsProduct::getProductNo, Function.identity(), (key1, key2) -> key2));
        // 如果物料不存在质检项，不需要创建
        ProductQualityItem searchProductItem = new ProductQualityItem();
        searchProductItem.setProductNos(productNos);
        List<ProductQualityItem> qualityItemList = this.productQualityItemService.selectProductQualityItemList(searchProductItem);
        Map<String,List<ProductQualityItem>> productNoAndItemMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(qualityItemList)){
            productNoAndItemMap = qualityItemList.stream().collect(Collectors.groupingBy(ProductQualityItem::getProductNo));
        }
        List<ProductQualityMainTask> addList = new ArrayList<>();
        for (ProductQualityMainTask productQualityMainTask : productQualityMainTaskList){
            if (CollectionUtils.isEmpty(productNoAndItemMap.get(productQualityMainTask.getProductNo()))){
                continue;
            }
            if(StringUtils.isBlank(productQualityMainTask.getNo())){
                productQualityMainTask.setNo(TableNoUtil.getNo(ProductQualityMainTask.class));
            }
            // 如果是来料检，需要按抽检比例计算抽检数量
            if (QualityTypeEnum.IQC.getCode().equals(productQualityMainTask.getQualityType())){
                // 查询对应的物料信息
                WmsProduct wmsProduct = productMap.get(productQualityMainTask.getProductNo());
                if (wmsProduct.getQualityRatio() != null){
                    // 抽检比例存的是百分比制，因此抽检数量结果要除100(总数量*抽检比例/100)
                    BigDecimal quantity = productQualityMainTask.getTotalQuantity().multiply(wmsProduct.getQualityRatio()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
                    productQualityMainTask.setQuantity(quantity);
                }else{
                    productQualityMainTask.setQuantity(productQualityMainTask.getTotalQuantity());
                }
            }
            productQualityMainTask.setCreateBy(username);
            productQualityMainTask.setCreateTime(currerTime);
            addList.add(productQualityMainTask);
        }
        int insertNum = 0;
        for (int i=0; i<addList.size();) {
            int endIndex = i+500;
            if (endIndex > addList.size()) {
                endIndex = addList.size();
            }
            insertNum = insertNum + productQualityMainTaskMapper.batchInsertProductQualityMainTask(addList.subList(i, endIndex));
            i = endIndex;
        }
        return insertNum;
    }

    /**
     * 修改物料质检项
     *
     * @param productQualityMainTask 物料质检项
     * @return 结果
     */
    @Override
    public int updateProductQualityMainTask(ProductQualityMainTask productQualityMainTask) {
        productQualityMainTask.setUpdateBy(SecurityUtils.getUsername());
        productQualityMainTask.setUpdateTime(DateUtils.getNowDate());
        return productQualityMainTaskMapper.updateProductQualityMainTask(productQualityMainTask);
    }

    /**
     * 完成物料质检任务
     *
     * @param productQualityMainTask 物料质检任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int complete(ProductQualityMainTask productQualityMainTask){
        // 查询质检任务
        ProductQualityMainTask searchTask = this.selectProductQualityMainTaskById(productQualityMainTask.getId());
        // 判断已完成数量是否大于等于主任务的检验数量
        if (searchTask.getInspectedQuantity().intValue() < searchTask.getQuantity().intValue()){
            throw new ServiceException("已检验数量未达到质检任务数量，无法完成");
        }
        searchTask.setStatus(QualityTaskStatusEnum.COMPLETED.getCode());
        searchTask.setFinishTime(new Date());
        searchTask.setQualityUserName(SecurityUtils.getUsername());
        searchTask.setProcessMode(productQualityMainTask.getProcessMode());
        searchTask.setQualityResult(productQualityMainTask.getQualityResult());
        searchTask.setUpdateTime(new Date());
        searchTask.setUpdateBy(SecurityUtils.getUsername());
        searchTask.setReturnQuantity(productQualityMainTask.getReturnQuantity());
        int updateNum  = productQualityMainTaskMapper.updateProductQualityMainTask(searchTask);
        // 2023-02-24 新增逻辑，如果是来料检，该来源单的所有质检任务是否都已检，统一生成出货单
        if (QualityTypeEnum.IQC.getCode().equals(searchTask.getQualityType()) && StringUtils.isNotEmpty(searchTask.getSourceNo())){
           if (searchTask.getInOrderDetailId()!=null){
               WmsInStockDetailOrder inStockDetailOrder = this.inStockDetailOrderService.selectWmsInStockDetailOrderById(searchTask.getInOrderDetailId());
               if (inStockDetailOrder!=null){
                  if(inStockDetailOrder.getWhetherWaitProduct()!=1){
                      //处理待检仓来料检
                      this.execDjcQuality(searchTask);
                  }else{
                      //处理已检仓来料检
                      this.execYjcQuality(searchTask);
                  }
                  }
           }else{
               throw new ServiceException("未绑定入库明细ID");
           }
        }
        if (QualityTypeEnum.OQC.getCode().equals(searchTask.getQualityType())){
            PickerTaskOrder oldTaskOrder = this.pickerTaskOrderService.selectPickerTaskOrderByNo(searchTask.getPickerTaskNo());
            if (oldTaskOrder != null) {
                // 如果选择报废，需要复制该拣货任务单，生成新的拣货任务单
                if (QualityProcessModeEnum.SCRAP.getCode().equals(productQualityMainTask.getProcessMode())){
                    WmsStorehouse storehouse = storehouseService.selectWmsStorehouseByNo(oldTaskOrder.getStorehouseNo()) ;
                    boolean stockFlag = true;
                    if (storehouse!=null){
                        //判断库存是否充足，如果充足生成新的拣货单，如果不足则不生成拣货单
                        if(StoreHouseTypeEnum.DJC.getCode().equals(storehouse.getTypeNo())){
                            StorehouseStockCheck check = new StorehouseStockCheck();
                            check.setStorehouseNo(oldTaskOrder.getStorehouseNo());
                            check.setProductNo(oldTaskOrder.getProductNo());
                            List<StorehouseStockCheck> checks = storehouseStockCheckService.selectStorehouseStockCheckList(check);
                            if(CollectionUtil.isEmpty(checks)){
                                stockFlag =false;
                            }
                        }else {
                            WmsStorehouseStock stock = new WmsStorehouseStock();
                            stock.setStorehouseNo(oldTaskOrder.getStorehouseNo());
                            stock.setProductNo(oldTaskOrder.getProductNo());
                            List<WmsStorehouseStock> stocks = wmsStorehouseStockService.selectWmsStorehouseStockList(stock);
                            if(CollectionUtil.isEmpty(stocks)){
                                stockFlag =false;
                            }
                        }
                    }
                    if (stockFlag){
                        // 复制生成新的拣货单
                        PickerTaskOrder addTaskOrder = new PickerTaskOrder();
                        BeanUtils.copyProperties(oldTaskOrder, addTaskOrder);
                        addTaskOrder.setNo(TableNoUtil.getNo(PickerTaskOrder.class));
                        addTaskOrder.setStatus(OutOrderStatusEnum.WAITING_PICK.getCode());
                        addTaskOrder.setCompleteTime(null);
                        addTaskOrder.setId(null);
                        addTaskOrder.setUpdateBy(null);
                        addTaskOrder.setUpdateTime(null);
                        addTaskOrder.setQualityTaskNo(null);
                        addTaskOrder.setPickingQty(null);
                        this.pickerTaskOrderService.insertPickerTaskOrder(addTaskOrder);
                        //库存占用处理
                        String taskNo = addTaskOrder.getNo();
                        String storehouseNo = addTaskOrder.getStorehouseNo();
                        String productNo = addTaskOrder.getProductNo();
                        Long orderQty = addTaskOrder.getDistributeQty();
                        wmsStockOccupyService.stockOccupy(taskNo,storehouseNo, productNo, orderQty,null,null, YNEnum.N.getCode());
                    }
                }
            }
            // 将拣货单状态修改为完成
            this.pickerTaskOrderService.complete(oldTaskOrder);
        }
        return updateNum;
    }

    /**
     * 处理已检仓来料检
     * @param searchTask
     */
    public void execYjcQuality(ProductQualityMainTask searchTask){
        //获取库存
        List<WmsStorehouseStock> storehouseStockList = this.wmsStorehouseStockService.getListByQualityTaskNo(searchTask.getNo());
        if (CollectionUtil.isNotEmpty(storehouseStockList)){
            // 如果处理方式不为空，说明质检不合格，需要判断状态
            String stockStatus = StorehouseStockStatusEnum.NORMAL.getCode();
            String qualityStatus = StockQualityStatusEnum.CHECKED.getCode();
            //是否生成退货单
            if (StringUtils.isNotEmpty(searchTask.getProcessMode())){
                if (QualityProcessModeEnum.CONCESSION.getCode().equals(searchTask.getProcessMode())){
                    stockStatus = StorehouseStockStatusEnum.POOR.getCode();
                }
                if (QualityProcessModeEnum.PART.getCode().equals(searchTask.getProcessMode())){
                    stockStatus = StorehouseStockStatusEnum.POOR.getCode();
                }
                if (QualityProcessModeEnum.RETURN.getCode().equals(searchTask.getProcessMode())){
                    searchTask.setReturnQuantity(searchTask.getTotalQuantity());
                    stockStatus = StorehouseStockStatusEnum.RETURNED.getCode();
                }
            }
            //更新库存
            for (WmsStorehouseStock stock: storehouseStockList){
                stock.setStatus(stockStatus);
                stock.setQualityStatus(qualityStatus);
            }
            this.wmsStorehouseStockService.batchUpdateWmsStorehouseStock(storehouseStockList);
        }
        //处理生成业务单
        this.execCreateOrder(searchTask,false);
    }
    /**
     * 处理待检仓来料检
     * @param searchTask
     */
    public void execDjcQuality(ProductQualityMainTask searchTask ){
        // 2022-03-09 需要更新对应的待检仓物料库存状态
        String status = StorehouseStockCheckStatusEnum.INSPECTED_QUALIFIED.getCode();
        // 如果处理方式不为空，说明质检不合格，需要判断状态
        if (StringUtils.isNotEmpty(searchTask.getProcessMode())){
            if (QualityProcessModeEnum.CONCESSION.getCode().equals(searchTask.getProcessMode())){
                status = StorehouseStockCheckStatusEnum.INSPECTED_CONCESSION.getCode();
            }
            if (QualityProcessModeEnum.PART.getCode().equals(searchTask.getProcessMode())){
                status = StorehouseStockCheckStatusEnum.INSPECTED_PART.getCode();
            }
            if (QualityProcessModeEnum.RETURN.getCode().equals(searchTask.getProcessMode())){
                status = StorehouseStockCheckStatusEnum.INSPECTED_RETURN.getCode();
                searchTask.setReturnQuantity(searchTask.getTotalQuantity());
            }
        }
        this.storehouseStockCheckService.updateStockStatusByTaskNo(searchTask.getNo(),status);
//        //处理生成业务单
        this.execCreateOrder(searchTask,true);
    }

    /**
     * 自动生成单据
     * @param searchTask 质检任务
     * @param isDjc 是否是待检仓
     */
    public void execCreateOrder(ProductQualityMainTask searchTask,boolean isDjc){
        int notFinishTaskNum = productQualityMainTaskMapper.getNotFinishTaskNumBySourceNo(searchTask.getSourceNo());
        if (notFinishTaskNum == 0){
            Integer returnType = PurchaseReturnBillReturnTypeEnum.WAIT_INSPECTION.getCode();
            if (!isDjc){
                returnType = PurchaseReturnBillReturnTypeEnum.INSPECTION.getCode();
            }
            ProductQualityMainTask searchSameEntity = new ProductQualityMainTask();
            searchSameEntity.setSourceNo(searchTask.getSourceNo());
            List<ProductQualityMainTask> sameSourceNoTaskList = this.selectProductQualityMainTaskList(searchSameEntity);
            ReceiveProductBill receiveProductBill = receiveProductBillService.selectReceiveProductBillByNo(searchTask.getSourceNo());
            // 采购退货单
            PurchaseReturnBill purchaseReturnBill = new PurchaseReturnBill();
            purchaseReturnBill.setReturnType(returnType);
            purchaseReturnBill.setReturnCause("质检不合格");
            purchaseReturnBill.setStatus(OutOrderStatusEnum.NEW.getCode());
            purchaseReturnBill.setNo(PrefixConstants.PURCHASE_RETURN+TableNoUtil.getNo(PurchaseReturnBill.class));
            List<PurchaseReturnBillDetail> returnDetailOrderList = new ArrayList<>();
            // 退货出库单
            WmsOutStockOrder wmsOutStockOrder = new WmsOutStockOrder();
            wmsOutStockOrder.setNo(TableNoUtil.getNo(WmsOutStockOrder.class));
            wmsOutStockOrder.setOrderStatus(OutOrderStatusEnum.NEW.getCode());
            wmsOutStockOrder.setOrderType(OutStockOrderTypeEnum.RETURN.getCode());
            wmsOutStockOrder.setRelOrderNo(purchaseReturnBill.getNo());
            wmsOutStockOrder.setCause("质检不合格");
            if (receiveProductBill != null){
                purchaseReturnBill.setSupplierName(receiveProductBill.getSupplierName());
                purchaseReturnBill.setSupplierNo(receiveProductBill.getSupplierNo());
                wmsOutStockOrder.setSupplierName(receiveProductBill.getSupplierName());
                wmsOutStockOrder.setSupplierNo(receiveProductBill.getSupplierNo());
            }
            List<WmsOutStockDetailOrder> outStockDetailOrderList = new ArrayList<>();
                // 收货入库单
                WmsInStockOrder inStockOrder = new WmsInStockOrder();
                inStockOrder.setOrderStatus(InOrderStatusEnum.NEW.getCode());
                inStockOrder.setRelOrderNo(searchTask.getSourceNo());
                inStockOrder.setOrderType(InStockOrderTypeEnum.RECEIVING.getCode());
                inStockOrder.setNo(TableNoUtil.getNo(WmsInStockOrder.class));
                List<WmsInStockDetailOrder> detailOrderList = new ArrayList<>();
                long sumQty = 0L;
                for (ProductQualityMainTask mainTask : sameSourceNoTaskList) {
                    //如果是待检仓，跳过先入库后检验的物料，如果不是，则跳过入待检仓的物料
                    if (isDjc){
                        if (mainTask.getInOrderDetailId()!=null){
                            WmsInStockDetailOrder stockDetailOrder = this.inStockDetailOrderService.selectWmsInStockDetailOrderById(mainTask.getInOrderDetailId());
                            if (stockDetailOrder!=null){
                                //如果是先入库后检验的物料直接跳过
                                if(stockDetailOrder.getWhetherWaitProduct().intValue()== WhetherEnum.Y.getCode()){
                                    continue;
                                }
                            }
                        }
                    }else{
                        if (mainTask.getInOrderDetailId()!=null){
                            WmsInStockDetailOrder stockDetailOrder = this.inStockDetailOrderService.selectWmsInStockDetailOrderById(mainTask.getInOrderDetailId());
                            if (stockDetailOrder!=null){
                                //如果不是先入库后检验的物料直接跳过
                                if(stockDetailOrder.getWhetherWaitProduct().intValue()!= WhetherEnum.Y.getCode()){
                                    continue;
                                }
                            }
                        }else{
                            continue;
                        }
                    }
                    boolean isCreateReturn = true;
                    boolean isCreateInStock = true;
                    // 如果是退货，不生成收货单
                    if (QualityProcessModeEnum.RETURN.getCode().equals(mainTask.getProcessMode())){
                        isCreateInStock = false;
                    }
                    // 如果是让步接收或合格，不生成退货单
                    if (QualityProcessModeEnum.CONCESSION.getCode().equals(mainTask.getProcessMode())
                            || QualityResultEnum.OK.getCode().equals(mainTask.getQualityResult())
                    ){
                        isCreateReturn = false;
                    }
                    if (isCreateInStock){
                        if (isDjc){
                            WmsInStockDetailOrder wmsInStockDetailOrder = new WmsInStockDetailOrder();
                            wmsInStockDetailOrder.setOrderNo(inStockOrder.getNo());
                            wmsInStockDetailOrder.setProductNo(mainTask.getProductNo());
                            wmsInStockDetailOrder.setProductName(mainTask.getProductName());
                            wmsInStockDetailOrder.setOrderDetailStatus(InOrderStatusEnum.NEW.getCode());
                            if(mainTask.getReturnQuantity()!=null){
                                wmsInStockDetailOrder.setOrderQty(mainTask.getTotalQuantity().longValue()-mainTask.getReturnQuantity().longValue());
                            }else{
                                wmsInStockDetailOrder.setOrderQty(mainTask.getTotalQuantity().longValue());
                            }
                            detailOrderList.add(wmsInStockDetailOrder);
                            sumQty += mainTask.getTotalQuantity().longValue();
                        }
                    }
                    if (isCreateReturn){
                        PurchaseReturnBillDetail purchaseReturnBillDetail = new PurchaseReturnBillDetail();
                        purchaseReturnBillDetail.setOrderNo(purchaseReturnBill.getNo());
                        purchaseReturnBillDetail.setProductNo(mainTask.getProductNo());
                        purchaseReturnBillDetail.setProductName(mainTask.getProductName());
                        purchaseReturnBillDetail.setOrderQty(mainTask.getReturnQuantity()==null?mainTask.getTotalQuantity().longValue():mainTask.getReturnQuantity().longValue());
                        returnDetailOrderList.add(purchaseReturnBillDetail);
                        WmsOutStockDetailOrder wmsOutStockDetailOrder = new WmsOutStockDetailOrder();
                        wmsOutStockDetailOrder.setOrderNo(wmsOutStockOrder.getNo());
                        wmsOutStockDetailOrder.setOrderDetailStatus(OutOrderStatusEnum.NEW.getCode());
                        wmsOutStockDetailOrder.setProductNo(mainTask.getProductNo());
                        wmsOutStockDetailOrder.setProductName(mainTask.getProductName());
                        wmsOutStockDetailOrder.setOrderQty(mainTask.getReturnQuantity()==null?mainTask.getTotalQuantity().longValue():mainTask.getReturnQuantity().longValue());
                        wmsOutStockDetailOrder.setReturnStorehouseName(mainTask.getStorehouseName());
                        wmsOutStockDetailOrder.setReturnStorehouseNo(mainTask.getStorehouseNo());
                        wmsOutStockDetailOrder.setPickingQty(0L);
                        outStockDetailOrderList.add(wmsOutStockDetailOrder);
                    }
                }
                inStockOrder.setTotalQty(sumQty);
                if (isDjc){
                    if (!CollectionUtils.isEmpty(detailOrderList)){
                        inStockOrderService.insertWmsInStockOrder(inStockOrder);
                        inStockDetailOrderService.batchInsertInStockDetailOrder(detailOrderList);
                    }
                }
                if (!CollectionUtils.isEmpty(returnDetailOrderList)){
                    returnBillService.insertPurchaseReturnBill(purchaseReturnBill);
                    returnBillDetailService.batchInsertPurchaseReturnBillDetail(returnDetailOrderList);
                    wmsOutStockOrderService.insertWmsOutStockOrder(wmsOutStockOrder);
                    wmsOutStockDetailOrderService.batchInsertOutStockDetailOrder(outStockDetailOrderList);
                    log.info("生成采购退货单成功");
                }
        }
    }
    /**
     * 批量修改物料质检项
     *
     * @param productQualityMainTaskList 物料质检项列表
     * @return 结果
     */
    @Override
    public int batchUpdateProductQualityMainTask(List<ProductQualityMainTask> productQualityMainTaskList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (ProductQualityMainTask productQualityMainTask : productQualityMainTaskList){
            productQualityMainTask.setUpdateBy(username);
            productQualityMainTask.setUpdateTime(currerTime);
        }
        int updateNum = 0;
        for (int i=0; i<productQualityMainTaskList.size();) {
            int endIndex = i+500;
            if (endIndex > productQualityMainTaskList.size()) {
                endIndex = productQualityMainTaskList.size();
            }
            updateNum = updateNum + productQualityMainTaskMapper.batchUpdateProductQualityMainTask(productQualityMainTaskList.subList(i, endIndex));
            i = endIndex;
        }
        return updateNum;
    }

    /**
     * 批量删除物料质检项
     *
     * @param ids 需要删除的物料质检项主键集合
     * @return 结果
     */
    @Override
    public int deleteProductQualityMainTaskByIds(Long[] ids) {
        return productQualityMainTaskMapper.deleteProductQualityMainTaskByIds(ids);
    }

    /**
     * 删除物料质检项信息
     *
     * @param id 物料质检项主键
     * @return 结果
     */
    @Override
    public int deleteProductQualityMainTaskById(Long id) {
        return productQualityMainTaskMapper.deleteProductQualityMainTaskById(id);
    }

    /**
     * 查询物料质检项
     *
     * @param no 编号
     * @return 物料质检项
     */
    @Override
    public ProductQualityMainTask selectProductQualityMainTaskByNo(String no) {
        return productQualityMainTaskMapper.selectProductQualityMainTaskByNo(no);
    }

    /**
     * 批量删除物料质检项
     *
     * @param nos 需要删除的编号集合
     * @return 结果
     */
    @Override
    public int deleteProductQualityMainTaskByNos(String[] nos) {
        return productQualityMainTaskMapper.deleteProductQualityMainTaskByNos(nos);
    }

    /**
     * 删除物料质检项信息
     *
     * @param no 编号
     * @return 结果
     */
    @Override
    public int deleteProductQualityMainTaskByNo(String no) {
        return productQualityMainTaskMapper.deleteProductQualityMainTaskByNo(no);
    }

    /**
     * 查询不合格的物料质检明细数量
     *
     * @param taskNo 质检任务编号
     * @return 不合格的项目数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer checkTaskNgNum(String taskNo){
        return this.productQualityMainTaskMapper.checkTaskNgNum(taskNo);
    }

    /**
     * 查询条码是否属于质检任务对应拣货单
     *
     * @param taskNo 质检任务号
     * @param barcode 条码
     *
     * @return 符合条件的数量
     */
    @Override
    public WmsPickingRecord checkTaskBarcode(String taskNo, String barcode){
        // 查询质检任务
        ProductQualityMainTask mainTask = this.selectProductQualityMainTaskByNo(taskNo);
        if (mainTask == null || StringUtils.isEmpty(mainTask.getPickerTaskNo())){
            throw new ServiceException("拣货任务不存在");
        }
        // 查询该拣货任务、条码对应的拣货记录
        WmsPickingRecord searchParam = new WmsPickingRecord();
        searchParam.setNo(mainTask.getPickerTaskNo());
        searchParam.setBarcode(barcode);
        return this.productQualityMainTaskMapper.checkTaskBarcode(searchParam);
    }
}
